package Aleehot100;

/**
 * ClassName: c026
 * Package: Aleehot100
 * Description: 返回有环链表的第一个 入环的节点
 *
 * @Author BCXJ
 * @Create 2025/6/13 20:01
 * @Version 1.0
 * @Since 1.0
 */
public class c026 {
    public static void main(String[] args) {

    }

    static class ListNode {
        int val;
        ListNode next;
        public ListNode(int val) {
            this.val = val;
            next = null;
        }
    }

    // public static ListNode detectCycle(ListNode head) {
    //     if (head == null || head.next == null || head.next.next == null) {
    //         return null;
    //     }
    //     ListNode slow = head.next, fast = head.next.next;
    //     while (slow != fast) {
    //         if (fast.next == null || fast.next.next == null) {
    //             return null;
    //         }
    //         slow = slow.next;
    //         fast = fast.next.next;
    //     }
    //     slow = head;
    //     while (slow != fast) {
    //         slow = slow.next;
    //         fast = fast.next;
    //     }
    //     return slow;
    // }


    public static ListNode detectCycle(ListNode head) {
        if(head == null) {
            return null;
        }
        ListNode fast = head, slow = head;
        while(fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) {
                slow = head;
                while(fast != slow) {
                    fast = fast.next;
                    slow = slow.next;
                }
                return slow;
            }
        }
        return null;
    }
}
